<template>
  <div class="reservation-container">
    <div class="header">
      <h2>预约管理</h2>
      <div class="filter-container">
        <el-select v-model="searchStatus" placeholder="预约状态" clearable @change="handleFilter">
          <el-option label="全部" value="" />
          <el-option label="待审核" :value="0" />
          <el-option label="已确认" :value="1" />
          <el-option label="已取消" :value="2" />
        </el-select>
        <el-date-picker
          v-model="searchDate"
          type="date"
          placeholder="参观日期"
          style="width: 200px"
          value-format="YYYY-MM-DD"
          @change="handleFilter"
        />
        <el-button type="primary" @click="handleFilter">筛选</el-button>
        <el-button @click="resetFilter">重置</el-button>
      </div>
    </div>
    
    <el-table
      v-loading="loading"
      :data="reservationList"
      style="width: 100%"
      border
    >
      <el-table-column prop="id" label="预约编号" width="100" />
      <el-table-column label="预约人" width="120">
        <template #default="scope">
          {{ scope.row.userId ? `用户${scope.row.userId}` : '未知用户' }}
        </template>
      </el-table-column>
      <el-table-column prop="visitorCount" label="参观人数" width="100" />
      <el-table-column label="参观日期" width="120">
        <template #default="scope">
          {{ scope.row.visitDate }}
        </template>
      </el-table-column>
      <el-table-column label="参观时段" width="150">
        <template #default="scope">
          {{ scope.row.visitTimeSlot }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="预约时间" width="180">
        <template #default="scope">
          {{ formatDateTime(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button
            size="small"
            @click="viewDetail(scope.row.id)"
          >
            详情
          </el-button>
          <el-button
            v-if="scope.row.status === 0"
            size="small"
            type="success"
            @click="confirmReservation(scope.row.id)"
          >
            确认
          </el-button>
          <el-button
            v-if="scope.row.status === 0"
            size="small"
            type="danger"
            @click="cancelReservation(scope.row.id)"
          >
            取消
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <div class="pagination">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        :current-page="currentPage"
        :page-size="pageSize"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getReservationList, updateReservationStatus } from '@/api/reservation'

const router = useRouter()
const loading = ref(false)
const reservationList = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const searchStatus = ref('')
const searchDate = ref('')

// 获取预约列表
const fetchReservationList = async () => {
  loading.value = true
  try {
    const res = await getReservationList({
      page: currentPage.value,
      size: pageSize.value,
      status: searchStatus.value,
      date: searchDate.value
    })
    console.log('预约数据响应:', res)
    if (res.code === 200) {
      reservationList.value = res.data.records || []
      total.value = res.data.total || 0
    } else {
      ElMessage.error(res.message || '获取预约列表失败')
    }
  } catch (error) {
    console.error('获取预约列表失败', error)
    ElMessage.error('获取预约列表失败')
  } finally {
    loading.value = false
  }
}

// 页面加载时获取数据
onMounted(() => {
  fetchReservationList()
})

// 分页变化
const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchReservationList()
}

// 处理筛选
const handleFilter = () => {
  currentPage.value = 1
  fetchReservationList()
}

// 重置筛选
const resetFilter = () => {
  searchStatus.value = ''
  searchDate.value = ''
  currentPage.value = 1
  fetchReservationList()
}

// 查看详情
const viewDetail = (id) => {
  router.push(`/reservation/detail/${id}`)
}

// 确认预约
const confirmReservation = (id) => {
  updateStatus(id, 1, '确认')
}

// 取消预约
const cancelReservation = (id) => {
  ElMessageBox.confirm('确定要取消该预约吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    updateStatus(id, 2, '取消')
  }).catch(() => {})
}

// 更新预约状态
const updateStatus = async (id, status, actionText) => {
  try {
    await updateReservationStatus(id, status)
    ElMessage.success(`${actionText}预约成功`)
    fetchReservationList()
  } catch (error) {
    console.error(`${actionText}预约失败`, error)
    ElMessage.error(`${actionText}预约失败`)
  }
}

// 获取状态类型
const getStatusType = (status) => {
  const types = ['warning', 'success', 'info']
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = ['待审核', '已确认', '已取消']
  return texts[status] || '未知'
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '';
  try {
    const date = new Date(dateTime);
    if (isNaN(date.getTime())) {
      return dateTime;
    }
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
  } catch (error) {
    return dateTime;
  }
}
</script>

<style scoped>
.reservation-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filter-container {
  display: flex;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>